<template>
<section style="width:100%;">
    <el-form :model="formData" ref="formData" size="large" :rules="rules" style="width:100%;">
        <el-table :data="companies" style="width: 100%;" row-key="cName">  <!--	行数据的 Key，用来优化 Table 的渲染 -->
            <el-table-column label="公司名称"
                prop="cName"
            >
            </el-table-column>
    <el-table-column label="科目余额表上传">
    <template slot-scope="scope">
    <el-form-item prop="subjectStatementFileId" size="mini">
        <!-- <div class="single-line"> -->
        <el-upload
          :multiple="false"
          :limit="1"
          :with-credentials="true"
          :on-remove="removeBalanceStatementFile"
          :on-exceed="onExceed"
          :data="{ key: 'subjectBalanceSheetFileId' }"
          accept=".xlsx,.xls"
          action="/upload/subjectBalanceSheet"
          :http-request="(file)=> {return uploadFile(file, scope)}"
          class="upload-item"
        >
          <el-button size="small" type="primary"
            >点击上传</el-button
          >
        </el-upload>
        <!-- </div> -->
      </el-form-item>
    </template>
    </el-table-column>
    <el-table-column label="资产负债表上传">
    <template slot-scope="scope">
    <el-form-item prop="balanceStatementFileId" size="mini">
        <div class="single-line">
        <el-upload
          :multiple="false"
          :limit="1"
          :with-credentials="true"
          :on-remove="removeBalanceStatementFile"
          :on-exceed="onExceed"
          :data="{ key: 'yearBalanceSheetFileId' }"
          accept=".xlsx,.xls"
          action="/upload/balanceStatement"
          :http-request="(file)=> {return uploadFile(file, scope)}"
          class="upload-item"
        >
          <el-button size="small" type="primary"
            >点击上传</el-button
          >
        </el-upload>
        </div>
      </el-form-item>
    </template>
    </el-table-column>
    <el-table-column label="现金流量表上传" v-if="false">
    <template slot-scope="scope">
    <el-form-item prop="cashFlowSheetFileId" size="mini" v-show="false">
        <div class="single-line">
        <el-upload
          :multiple="false"
          :limit="1"
          :with-credentials="true"
          :on-remove="removeBalanceStatementFile"
          :on-exceed="onExceed"
          :data="{ key: 'cashFlowSheetFileId' }"
          accept=".xlsx,.xls"
          action="/upload/cashFlowSheet"
          :http-request="(file)=> {return uploadFile(file, scope)}"
          class="upload-item"
        >
          <el-button size="small" type="primary"
            >点击上传</el-button
          >
        </el-upload>
        </div>
      </el-form-item>
    </template>
    </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" align="left" @click="save(scope)">保存
                    </el-button>
                </template>
            </el-table-column>
</el-table>
</el-form>
</section>
</template>
<script>
import 'element-ui/lib/theme-chalk/upload.css';
import bankStatementUpload from '@/components/bankStatementUpload';
import utiles from "@/components/utiles";

export default {
    props: {
        accountBillData: {
            type: Object,
            default: null
        },

    },
    components: {
        bankStatementUpload
    },
    data() {
        return {
            companies:[],
            cashFlowSheetFileIdMap:{"公司1":[{name:"haha.xlxs"}]},
            yearBalanceSheetFileIdMap:{},
            subjectBalanceSheetFileIdMap:{},
            bName:"",
            uidFileidMap: {},
            typeMap:{
                "invoice": 0,
                "bankSlip": 1,
                "specInvoice":2
            },
            banktype:1,
            uploadBankFinished: false

        };
    },
    mounted(){
        const currentUser = utiles.getCurrentUser();
        this.bName = currentUser.bCompanyName;
        this.$http.get("/batchInput/showBaseInfo", {params:{bName: this.bName}}).then((res) => {
            if (res.code == 0){
                this.companies = res.data;
            }
        });
    },
    methods: {

        /**
         * 上传文件，当一次性选择多个文件时，会分多次上传
         *
         * @param {Object} fileData 文件数据
         */
    uploadFile(fileData, scope) {
      const formData = new FormData();
      // 键值
      formData.append("file", fileData.file);
      formData.append('companyName', scope.row.cName);
      this.$http.post(fileData.action, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this[`${fileData.data.key}Map`][scope.row.cName] = [{fileId:res.data.fileId, name: fileData.file.name}];
        })
        .catch((err) => {
          console.error(err);
        });
    },

    save(scope){
        // if (this.cashFlowSheetFileIdMap[scope.row.cName] != undefined
        //     || this.yearBalanceSheetFileIdMap[scope.row.cName] != undefined
        //     || this.subjectBalanceSheetFileIdMap[scope.row.cName] != undefined){
                console.log("sanbiao：", this.cashFlowSheetFileIdMap[scope.row.cName], this.yearBalanceSheetFileIdMap[scope.row.cName],
                this.subjectBalanceSheetFileIdMap[scope.row.cName])
                this.$http.post("/batchInput/save3Excel",
                {   
                    cName: scope.row.cName,
                    bName: this.bName,
                    balanceStatementId: this.yearBalanceSheetFileIdMap[scope.row.cName] != undefined ?this.yearBalanceSheetFileIdMap[scope.row.cName][0].fileId:"", //资产负债表
                    subjectBalanceSheetId: this.subjectBalanceSheetFileIdMap[scope.row.cName] != undefined?this.subjectBalanceSheetFileIdMap[scope.row.cName][0].fileId:"", //科目余额表
                    cashFlowSheetFileId: this.cashFlowSheetFileIdMap[scope.row.cName] != undefined?this.cashFlowSheetFileIdMap[scope.row.cName][0].fileId:"", // 利润表
                }).then((res) => {
                    if (res.code == 0){
                        let index = this.companies.findIndex(item => item.cName == scope.row.cName);
                        this.companies.splice(index, 1);
                        this.cashFlowSheetFileIdMap[scope.row.cName] = undefined,
                        this.yearBalanceSheetFileIdMap[scope.row.cName] = undefined,
                        this.subjectBalanceSheetFileIdMap[scope.row.cName] = undefined,
                        this.$message.success("保存成功");
                    }else{
                        return this.$message.error("保存失败：",  res.message);
                    }
                })
                
                // this.companies = Object.assign([],this.companies)
                // this.$set(this.$refs.multipleTable.tableData,scope.$index,this.companies[scope.$index]);
        // } else{
        //     this.$http.post("/batchInput/save3Excel",
        //         {   
        //             cName: scope.row.cName,
        //             bName: this.bName,
        //             balanceStatementId: "", //资产负债表
        //             subjectBalanceSheetId: "", //科目余额表
        //             cashFlowSheetFileId: "", // 利润表
        //         }).then((res) => {
        //             if (res.code == 0){
        //                 let index = this.companies.findIndex(item => item.cName == scope.row.cName);
        //                 this.companies.splice(index, 1);
        //                 this.$message.success("保存成功");
        //             }else{
        //                 return this.$message.error("保存失败：",  res.message);
        //             }
        //         })
        //         // this.cashFlowSheetFileIdMap[scope.row.cName] = []
        //         // this.yearBalanceSheetFileIdMap[scope.row.cName] = []
        //         // this.subjectBalanceSheetFileIdMap[scope.row.cName] = []
        // }
    },
        handleRemove(file, fileList){
            const deleteApi = "/upload/deleteInvoiceBankSlip";
            const {fileId: fileId, key: key, type: type} = this.uidFileidMap[file.uid]
            const params ={fileId:fileId,
                    companyName: this.accountBillData.companyName,
                    type: type
                    };
            // uploadFiles.splice(index, 1);
            this.$http.get(deleteApi, {params: params}).then(res => {
                if (res.code == 0) {
                    const index = this[`${key}FileIds`].findIndex(item => item == fileId);
                    this[`${key}FileIds`].splice(index, 1);
                    return true;
                }
                else {
                    this.$message.error(`${file.name}删除失败`);
                    return false;
                    // 从列表中删除上传失败的文件
                }
            })
        },
        getValue() {
          let bankStatementFileIds = [];
        //   if (!this.uploadFinished){
        //         var start = new Date();
        //         while(new Date() - start < 3000) { // delay 2 sec
        //             ;
        //         }
        //         this.uploadFinished = false;
        //     }

            if (this.$refs.bankStatementUploadInSpecial) {
                bankStatementFileIds = this.$refs.bankStatementUploadInSpecial.getValue();
            }

            return {
                invoiceFileIds: this.invoiceFileIds,
                bankSlipFileIds: this.bankSlipFileIds,
                specInvoiceFileIds: this.specInvoiceFileIds,
                bankStatementFileIds
            };
        },
        getUploadFinished(uploadFinished) {
            this.uploadBankFinished = uploadFinished;
            console.log("uploadBankFinished", this.uploadBankFinished)
            this.$emit("uploadBankFinished", this.uploadBankFinished);
            this.uploadBankFinished = false;
        }
    },
    watch:{
        banktype(newValue, oldValue){
            if (newValue == 1){
                this.uploadBankFinished = false;
                this.$emit("uploadBankFinished", this.uploadBankFinished);
            }else {
                this.uploadBankFinished = true;
                this.$emit("uploadBankFinished", this.uploadBankFinished);
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import '../../../assets/var.less';

// .el-table /deep/ .cell{
//     padding-right:0;
// }


.upload-item{
    width:100%;
    //display: inline-block;
}
.upload-item /deep/ .el-upload{
    align-items: center;
    float:left;
}
.upload-item /deep/ .el-upload-list{
    align-items: center;
    width:59%;
    display: block;
    float:left;
    .is-ready{
        float: right;
        display: block;
        margin-top:0;
    }
}

// #bankicon{
//     margin-top:0;
// }

// /deep/ 可以不必是父子组件关系
#bankupload /deep/ .el-upload{
    height: 100px;
    width: 100%;
}
#bankupload /deep/ .el-upload-dragger{
    height: 215px;
    width: 100%;
}

.form-item{
    width:100%;
}
.form-item #header-radio{
    width: 100%;
    height: 80px;
    padding-bottom: 20px;
    padding-left:10px;
    .el-upload__tip{
        text-align: left;
    }
}

.el-form-item{
    margin-bottom:0;
}


</style>